//! 配置系统

use serde::{Deserialize, Serialize};
use std::path::Path;
use crate::error::{UnicharError, Result};

/// 显示样式
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Style {
    /// 简单字符样式
    Simple,
    /// 图标样式
    Icon,
    /// 粗体样式
    Bold,
    /// 彩色样式
    Color,
    /// 自定义样式
    Custom(String),
}

impl Default for Style {
    fn default() -> Self {
        Style::Simple
    }
}

impl std::fmt::Display for Style {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Style::Simple => write!(f, "simple"),
            Style::Icon => write!(f, "icon"),
            Style::Bold => write!(f, "bold"),
            Style::Color => write!(f, "color"),
            Style::Custom(name) => write!(f, "custom:{}", name),
        }
    }
}

impl std::str::FromStr for Style {
    type Err = UnicharError;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "simple" => Ok(Style::Simple),
            "icon" => Ok(Style::Icon),
            "bold" => Ok(Style::Bold),
            "color" => Ok(Style::Color),
            custom if custom.starts_with("custom:") => {
                let name = custom.strip_prefix("custom:").unwrap_or("").to_string();
                Ok(Style::Custom(name))
            }
            _ => Err(UnicharError::ConfigError {
                message: format!("Unknown style: {}", s),
            }),
        }
    }
}

/// 配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// 默认样式
    pub style: Style,
    /// 是否启用颜色
    pub enable_color: bool,
    /// 是否启用ANSI转义序列
    pub enable_ansi: bool,
    /// 自定义样式映射
    pub custom_styles: std::collections::HashMap<String, Style>,
    /// 字符别名映射
    pub aliases: std::collections::HashMap<String, String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            style: Style::Simple,
            enable_color: false,
            enable_ansi: true,
            custom_styles: std::collections::HashMap::new(),
            aliases: std::collections::HashMap::new(),
        }
    }
}

impl Config {
    /// 创建新的配置
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置默认样式
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// 启用/禁用颜色
    pub fn with_color(mut self, enable: bool) -> Self {
        self.enable_color = enable;
        self
    }

    /// 启用/禁用ANSI转义序列
    pub fn with_ansi(mut self, enable: bool) -> Self {
        self.enable_ansi = enable;
        self
    }

    /// 添加自定义样式映射
    pub fn add_custom_style(mut self, name: String, style: Style) -> Self {
        self.custom_styles.insert(name, style);
        self
    }

    /// 添加字符别名
    pub fn add_alias(mut self, alias: String, target: String) -> Self {
        self.aliases.insert(alias, target);
        self
    }

    /// 从JSON字符串加载配置
    pub fn from_json(json: &str) -> Result<Self> {
        let config: Config = serde_json::from_str(json)?;
        Ok(config)
    }

    /// 将配置保存为JSON字符串
    pub fn to_json(&self) -> Result<String> {
        let json = serde_json::to_string_pretty(self)?;
        Ok(json)
    }

    /// 从文件加载配置
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        Self::from_json(&content)
    }

    /// 保存配置到文件
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let json = self.to_json()?;
        std::fs::write(path, json)?;
        Ok(())
    }

    /// 解析字符名称，处理别名
    /// 
    /// 返回解析后的字符名称，如果有别名则返回别名目标，否则返回原名称
    pub fn resolve_character_name(&self, name: &str) -> String {
        self.aliases.get(name).cloned().unwrap_or_else(|| name.to_string())
    }

    /// 获取样式优先级列表（用于回退）
    pub fn get_style_fallback(&self) -> Vec<Style> {
        let mut styles = vec![self.style.clone()];
        
        // 添加回退样式
        match self.style {
            Style::Icon => styles.extend([Style::Simple, Style::Bold]),
            Style::Color => styles.extend([Style::Icon, Style::Simple]),
            Style::Bold => styles.push(Style::Simple),
            Style::Simple => {}, // 简单样式已经是最后回退
            Style::Custom(_) => styles.extend([Style::Icon, Style::Simple]),
        }
        
        styles
    }
}

/// 预定义的配置预设
pub struct Presets;

impl Presets {
    /// 终端友好的配置（禁用颜色和ANSI）
    pub fn terminal() -> Config {
        Config::new()
            .with_style(Style::Simple)
            .with_color(false)
            .with_ansi(false)
    }

    /// 富文本配置（启用图标和颜色）
    pub fn rich() -> Config {
        Config::new()
            .with_style(Style::Icon)
            .with_color(true)
            .with_ansi(true)
    }

    /// 简洁配置（仅使用简单字符）
    pub fn minimal() -> Config {
        Config::new()
            .with_style(Style::Simple)
            .with_color(false)
            .with_ansi(false)
    }

    /// 开发配置（启用所有功能）
    pub fn development() -> Config {
        Config::new()
            .with_style(Style::Icon)
            .with_color(true)
            .with_ansi(true)
            .add_alias("ok".to_string(), "success".to_string())
            .add_alias("fail".to_string(), "error".to_string())
            .add_alias("warn".to_string(), "warning".to_string())
    }
}